// 导航守卫 页面访问权限
import router from './router'
import store from './store'

// 全局前置导航守卫：本质上就是在路由页面跳转之前会触发的一个函数
router.beforeEach(async(to, from, next) => {
  if (store.state.user.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.state.user.userInfo.id) {
        const res = store.state.user.user
        await store.dispatch('user/getUserInfo', res)
        await store.dispatch('user/getPermission')
        const menus = store.state.user.permission.menus
        await store.dispatch('permission/filterRoutes', menus)
        const routes = store.state.permission.routes
        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])
        return next(to.path)
      }
      next()
    }
  } else {
    const writeArr = ['/login', '/404', '/register']
    if (writeArr.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
